/*
 * @(#)CommandType.java
 *
 *
 *
 * ver 1.0 Aug 17, 2007 ggranum
 */
package org.testfire.model.commandtypes;

import java.util.HashMap;
import java.util.Map;
import org.testfire.model.ObjectWrapper;
import org.testfire.model.TestFireObject;
import org.testfire.model.TestsetType;
import org.testfire.translator.TranslatorFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.TypeInfo;

public abstract class CommandType implements TestFireObject
{
    private TestFireObject parent;

    String name;

    /**
     * As defined by attributes and their values.
     * At some point it may be desirable to handle child elements.
     * For now, however, I just can't bring myself to care about the one case I see a need.
     */
    Map<String, ObjectWrapper> params = new HashMap<String, ObjectWrapper>();

    public CommandType( Element element )
    {
        this.parse( element );
    }

    public void setParent( TestFireObject parent )
    {
        this.parent = parent;
    }

    public TestFireObject getParent()
    {
        return parent;
    }

    public void parse( Element el )
    {
        name = el.getLocalName();
        NamedNodeMap map = el.getAttributes();
        int len = map.getLength();
        for ( int i = 0; i < len; i++ )
        {
            Attr attr = (Attr)map.item( i );
            params.put( attr.getName(), new ObjectWrapper( attr ) );
        }


    }

    public Object translate( TestsetType testset )
    {
        return TranslatorFactory.translate( testset,  this );
    }

    public static CommandType createCommand( Element element )
    {
        if ( element.getSchemaTypeInfo().isDerivedFrom( "TestFire", "VoidCommand", TypeInfo.DERIVATION_EXTENSION )
            || element.getSchemaTypeInfo().getTypeName().equals( "VoidCommand" ) )
        {
            return new VoidCommandType( element );
        }
        if ( element.getSchemaTypeInfo().isDerivedFrom( "TestFire", "StringCommand", TypeInfo.DERIVATION_EXTENSION )
            || element.getSchemaTypeInfo().getTypeName().equals( "StringCommand" ) )
        {
            return new StringCommandType( element );
        }
        if ( element.getSchemaTypeInfo().isDerivedFrom( "TestFire", "ObjectCommand", TypeInfo.DERIVATION_EXTENSION )
            || element.getSchemaTypeInfo().getTypeName().equals( "ObjectCommand" ) )
        {
            return new ObjectCommandType( element );
        }
        return null;
    }

    public String getName()
    {
        return name;
    }

    public ObjectWrapper getParameter( String key )
    {
        return this.params.get( key );
    }

    public Map<String, ObjectWrapper> getParameters()
    {
        return params;
    }
}

// eof: CommandType.java